package com.c8a.validation.utils.valid;

import com.c8a.validation.annotation.ValidPassword;
import org.passay.*;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;

/**
 * @Author C8A
 * @Date 2022-04-24 17:28
 * @Email 1912327276@qq.com
 */

public class PasswordValidtion implements ConstraintValidator<ValidPassword, String> {

    @Override
    public boolean isValid(String password, ConstraintValidatorContext context) {

        PasswordValidator passwordValidator = new PasswordValidator(Arrays.asList(
                //8到30位
                new LengthRule(8, 30),
                //至少有一个英文的大写字母
                new CharacterRule(EnglishCharacterData.UpperCase, 1),
                //至少有一个英文的小写字母
                new CharacterRule(EnglishCharacterData.LowerCase, 1),
                //至少有一个英文的特殊字符
                new CharacterRule(EnglishCharacterData.Special, 1),
                //不允许有5个连续的英文字母
                new IllegalSequenceRule(EnglishSequenceData.Alphabetical, 5, false),
                //不允许有5个连续的数字
                new IllegalSequenceRule(EnglishSequenceData.Numerical, 5, false),
                //不允许有5个键盘连续的字母
                new IllegalSequenceRule(EnglishSequenceData.USQwerty, 5, false),
                //需要有空格
                new WhitespaceRule()
        ));

        RuleResult validateResult = passwordValidator.validate(new PasswordData(password));
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(String.join(",", passwordValidator.getMessages(validateResult)))
                .addConstraintViolation();
        return validateResult.isValid();
    }
}
